package com.hfb.mashibing.alip8.jvm.asm;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;

/**
 * 把 .class 文件反编译成 .java 源码
 */
public class ClassPrinter implements ClassVisitor {

//    public ClassPrinter() {super(ASM4);
//    }


    public static void main(String[] args) throws IOException {
//        ClassReader cr = new ClassReader("java.lang.Runnable");
        ClassReader cr = new ClassReader(
            ClassReader.class.getClassLoader().getResourceAsStream(
                "com/hfb/mashibing/alip8/jvm/asm/Test.class"));

        cr.accept(new ClassPrinter(), 0);
    }

    @Override
    public void visit(int version, int access, String name, String signature, String supperName, String[] interfaces) {
        System.out.println("public class "+name +" extends "+ supperName +" {");
    }

    @Override
    public void visitSource(String s, String s1) {

    }

    @Override
    public void visitOuterClass(String s, String s1, String s2) {

    }

    @Override
    public AnnotationVisitor visitAnnotation(String s, boolean b) {
        return null;
    }

    @Override
    public void visitAttribute(Attribute attribute) {

    }

    @Override
    public void visitInnerClass(String s, String s1, String s2, int i) {

    }

    @Override
    public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
        System.out.println("\t"+ name);
        return null;
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
//        System.out.println("descriptor: "+descriptor);
        if (descriptor.contains("L")) { // 有返回值
            String[] desc = descriptor.split("L");
            String res = desc[1].replace(";","")
                                .replace("/",".");

            System.out.printf("\t%s %s %s {//...}\n", res, name, desc[0]);
        } else { // 无返回值
            System.out.println("\t" + name+" "+"() {//...}");
        }
        return null;
    }

    @Override
    public void visitEnd() {
        System.out.println("}");
    }
}
class Test {
    private int i;
    private ArrayList li = new ArrayList();

    public Test() {super();}
    public Test(int i) {
    }

    public Object get(int i){
        return li.get(i);
    }
    public int getIndex(){
        return i;
    }
}
